package com.sevntu.apvs.gui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

/**
 * @author Solid
 * 
 */
public class GUIContentProvider {

	private static final Logger LOG = Logger.getLogger(Class.class.getName());

	public String loadFile(File file) throws Exception {
		String data = null;
		BufferedReader infile = new BufferedReader(new FileReader(file));
		StringBuilder input = new StringBuilder();
		String in;
		boolean firstLine = true;
		while ((in = infile.readLine()) != null) {
			if (!firstLine) {
				input.append("\n");
			}
			input.append(in);
			firstLine = false;
		}
		infile.close();
		data = input.toString();
		return data;
	}

	public void saveFile(File file, String data) throws FileNotFoundException {
		PrintWriter outfile = new PrintWriter(file);
		outfile.print(data);
		outfile.close();
	}

	/**
	 * Check whether folder exists. If not - create it.
	 * 
	 * @param folder
	 *            - relative folder path
	 * @return <code>true</code> if folder exists or was created or
	 *         <code>false</code> in another case.
	 */
	public boolean isFolderExist(File folder) {
		boolean result = true;
		if (!folder.exists()) {
			try {
				result = folder.getCanonicalFile().mkdirs();
			} catch (IOException e) {
				LOG.error("Unnable to create folder for results: " + folder, e);
			}
		}
		return result;
	}
}
